package com.psak.cudaphrasal.server;

import java.io.File;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.psak.cudaphrasal.model.FileChunkToProcess;
import com.psak.cudaphrasal.server.service.chunk.ChunkCreatorService;
import com.psak.cudaphrasal.server.service.inputfile.InputFileManagementService;
import com.psak.cudaphrasal.server.service.inputfile.InputFileManagementServiceException;
import com.psak.cudaphrasal.server.service.task.TaskDispatcherService;
import com.psak.cudaphrasal.server.service.task.TaskDispatcherServiceException;

/**
 * Entry point serwera.
 * 
 * @author piotrs10
 * 
 */
public class AppServer {
	public static void main(String[] args) {
		ApplicationContext context = loadContext(args);
		InputFileManagementService inputFileManagementService = ServiceLocator
				.getInputFileManagementService(context);
		ChunkCreatorService chunkCreatorService = ServiceLocator
				.getChunkCreatorService(context);
		TaskDispatcherService taskDispatcherService = ServiceLocator
				.getTaskDispatcherService(context);

		try {
			List<Long> wordHashList = inputFileManagementService
					.convertFileToWordHashList();
			List<FileChunkToProcess> chunks = chunkCreatorService
					.createChunks(wordHashList);
			taskDispatcherService.dispatchTasks(chunks);
		} catch (InputFileManagementServiceException e) {
			System.err.println(e.toString());
		} catch (TaskDispatcherServiceException e) {
			System.err.println(e.toString());
		}
	}

	private static ApplicationContext loadContext(String[] args) {
		if (args.length == 0) {
			return new ClassPathXmlApplicationContext("beans.xml");
		} else {
			String configPath = args[0];
			return new FileSystemXmlApplicationContext(configPath);
		}

	}
}
